﻿using System;
using System.Data.Common;
using System.Data.SqlClient;
using MySqlConnector;

namespace Sanhao.DbService
{
    public class DbFactory
    {
        private readonly DbProvider _dbProvider;

        public DbFactory(DbProvider dbProvider)
        {
            _dbProvider = dbProvider;
        }

        public DbConnection CreateDbConnection(string strConn)
        {
            DbConnection connection = null;
            switch (_dbProvider)
            {
                case DbProvider.MySql:
                    connection = new MySqlConnection(strConn);
                    break;
                case DbProvider.SqlServer:
                    connection = new SqlConnection(strConn);
                    break;
            }

            if (connection == null)
            {
                throw new Exception("cannot create connection");
            }

            return connection;
        }

        public DbCommand CreateDbCommand(string strSql, DbConnection conn)
        {
            DbCommand dbCommand = null;
            switch (_dbProvider)
            {
                case DbProvider.MySql:
                    dbCommand = new MySqlCommand(strSql, conn as MySqlConnection);
                    break;
                case DbProvider.SqlServer:
                    dbCommand = new SqlCommand(strSql, conn as SqlConnection);
                    break;
            }

            if (dbCommand == null)
            {
                throw new Exception("cannot create command");
            }

            return dbCommand;
        }

        public DbDataAdapter CreateDbDataAdapter(string strSql, DbConnection conn)
        {
            DbDataAdapter adapter = null;
            switch (_dbProvider)
            {
                case DbProvider.MySql:
                    adapter = new MySqlDataAdapter(strSql, conn as MySqlConnection);
                    break;
                case DbProvider.SqlServer:
                    adapter = new SqlDataAdapter(strSql, conn as SqlConnection);
                    break;
            }

            if (adapter == null)
            {
                throw new Exception("cannot create adapter");
            }

            return adapter;
        }

        public DbParameter CreateDbParameter(string parameterName, object value)
        {
            DbParameter param = null;
            switch (_dbProvider)
            {
                case DbProvider.MySql:
                    param = new MySqlParameter(parameterName, value);
                    break;
                case DbProvider.SqlServer:
                    param = new SqlParameter(parameterName, value);
                    break;
            }

            if (param == null)
            {
                throw new Exception("cannot create parameter");
            }

            return param;
        }

    }
}

